﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Common;
using ESOL.Business.Inv;
using ESOL.WinUI.Bpt;

namespace ESOL.WinUI.Inv
{
    public partial class frmMaintainStorageChange : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public InvStorageEntity SelectedInvStorage { get; set; }
        public InvDivertOrderEntity selectedDivertOrder { get; set; }
        #endregion

        #region Constructor
        public frmMaintainStorageChange()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "ICO", true);
        }
        private void SetField()
        {
            if (selectedDivertOrder == null)
            {
                return;
            }
            cmbStatus.SelectedValue = selectedDivertOrder.Status;
            dtpOrderTime.EditValue = selectedDivertOrder.OrderDate;
            txtOrderCode.Text = selectedDivertOrder.OrderCode;
            txtRelatedOrder.Text = selectedDivertOrder.RelatedOrder;
            txtCreatDate.Text = selectedDivertOrder.CreatedDate.ToString();
            txtLastModifyDate.Text = selectedDivertOrder.LastModifiedDate.ToString();
            txtRemark.Text = selectedDivertOrder.Remark;
            if (selectedDivertOrder.ApprovedDate.ToString("yyyy-MM-dd").Equals("0001-01-01"))
            {
                txtApprovedDate.Text = "";
            }
            else
            {
                txtApprovedDate.Text = selectedDivertOrder.ApprovedDate.ToString();
            }

            MstPersonEntity entity = MstPersonBs.GetMstPersonByID(selectedDivertOrder.CreatedBy);
            MstPersonEntity entity2 = MstPersonBs.GetMstPersonByID(selectedDivertOrder.LastModifiedBy);
            MstPersonEntity entity3 = MstPersonBs.GetMstPersonByID(selectedDivertOrder.ApprovedBy);
            if (entity != null)
            {
                txtCreatPerson.Text = entity.NameCn;
            }
            if (entity2 != null)
            {
                txtLastModifyPerson.Text = entity2.NameCn;
            }
            if (entity3 != null)
            {
                txtApprovedPerson.Text = entity3.NameCn;
            }

        }
        private void BindDataGrid()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("PRODUCT_NAME");
            dt.Columns.Add("PRODUCT_CODE");
            dt.Columns.Add("PRODUCT_ID");
            dt.Columns.Add("WAREHOUSE_NAME_OLD");
            dt.Columns.Add("WAREHOUSE_NAME_NEW");
            dt.Columns.Add("LOCATION_CODE_OLD");
            dt.Columns.Add("LOCATION_CODE_NEW");
            dt.Columns.Add("LOCATION_ID_OLD");
            dt.Columns.Add("LOCATION_ID_NEW");
            dt.Columns.Add("INV_QTY");
            dt.Columns.Add("OUT_QTY",typeof(decimal));
            //dt.Columns.Add("IN_QTY");
            dt.Rows.Add();
            if (ThisActionType == ActionType.New)
            {
                if (SelectedInvStorage != null)
                {
                    dt.Rows[0]["PRODUCT_NAME"] = MstProductBs.GetMstProductTypeByID(SelectedInvStorage.ProductId).ProductName;
                    dt.Rows[0]["PRODUCT_CODE"] = MstProductBs.GetMstProductTypeByID(SelectedInvStorage.ProductId).ProductCode;
                    dt.Rows[0]["INV_QTY"] = SelectedInvStorage.CurrentQty.ToString();
                    dt.Rows[0]["WAREHOUSE_NAME_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(SelectedInvStorage.LocationId).Rows[0]["WAREHOUSE_NAME"].ToString();
                    dt.Rows[0]["LOCATION_CODE_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(SelectedInvStorage.LocationId).Rows[0]["LOCATION_CODE"].ToString();
                    dt.Rows[0]["LOCATION_ID_OLD"] = SelectedInvStorage.LocationId;
                    dt.Rows[0]["PRODUCT_ID"] = SelectedInvStorage.ProductId;
                    dt.Rows[0]["OUT_QTY"] = 0;
                   // dt.Rows[0]["IN_QTY"] = 0;
                    gvDetail.DataSource = dt;
                }
                else
                {
                    dt.Rows[0]["OUT_QTY"] = 0;
                    gvDetail.DataSource = dt;
                }

            }
            else
            {
                if (selectedDivertOrder == null)
                {
                    return;
                }
                MstProductEntity product = MstProductBs.GetMstProductTypeByID(selectedDivertOrder.ProductId);
                dt.Rows[0]["PRODUCT_NAME"] = product.ProductName;
                dt.Rows[0]["PRODUCT_CODE"] = product.ProductCode;

                dt.Rows[0]["INV_QTY"] = InvStorageBs.GetInvStorageByProdAndLocation(selectedDivertOrder.ProductId, selectedDivertOrder.OutLocationId).Rows[0]["CURRENT_QTY"].ToString();
                dt.Rows[0]["WAREHOUSE_NAME_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(selectedDivertOrder.OutLocationId).Rows[0]["WAREHOUSE_NAME"].ToString();
                dt.Rows[0]["LOCATION_CODE_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(selectedDivertOrder.OutLocationId).Rows[0]["LOCATION_CODE"].ToString();
                dt.Rows[0]["LOCATION_ID_OLD"] = selectedDivertOrder.OutLocationId;
                dt.Rows[0]["WAREHOUSE_NAME_NEW"] = MstLocationBs.GetWarehouseLocationByLocationId(selectedDivertOrder.InLocationId).Rows[0]["WAREHOUSE_NAME"].ToString();
                dt.Rows[0]["LOCATION_CODE_NEW"] = MstLocationBs.GetWarehouseLocationByLocationId(selectedDivertOrder.InLocationId).Rows[0]["LOCATION_CODE"].ToString();
                dt.Rows[0]["LOCATION_ID_NEW"] = selectedDivertOrder.InLocationId;

                dt.Rows[0]["PRODUCT_ID"] = selectedDivertOrder.ProductId;
                dt.Rows[0]["OUT_QTY"] = selectedDivertOrder.Qty;
                gvDetail.DataSource = dt;
            }

            
        }
        private bool CheckData()
        {
            DataTable dt = gvDetail.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["PRODUCT_CODE"].ToString()))
                {
                    MessageBox.Show("请输入物品编码", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                if (string.IsNullOrEmpty(dr["LOCATION_CODE_OLD"].ToString()) || string.IsNullOrEmpty(dr["LOCATION_CODE_NEW"].ToString()))
                {
                    MessageBox.Show("请输入移库库位", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
                if (string.IsNullOrEmpty(dr["OUT_QTY"].ToString()) || dr["OUT_QTY"].ToString()=="0")
                {
                    MessageBox.Show("请输入移库数量", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            return true;
        }
        private void SetEntity()
        {
            DataTable dt = (DataTable)gvDetail.DataSource;
            
            selectedDivertOrder = new InvDivertOrderEntity();
            

            selectedDivertOrder.OrderType = "IDT06";
            selectedDivertOrder.OrderPerson = CommonParameter.CurrentUser.PersonId;
            selectedDivertOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            selectedDivertOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            if (dtpOrderTime.EditValue != null)
            {
                selectedDivertOrder.OrderDate = Convert.ToDateTime(dtpOrderTime.EditValue.ToString());
            }
            selectedDivertOrder.CreatedDate = DateTime.Now;
            selectedDivertOrder.LastModifiedDate = DateTime.Now;
            selectedDivertOrder.Remark = txtRemark.Text;
            if (txtRelatedOrder.Text != null)
            {
                selectedDivertOrder.RelatedOrder = txtRelatedOrder.Text;
            }
            foreach (DataRow dr in dt.Rows)
            {
                selectedDivertOrder.ProductId = dr["PRODUCT_ID"].ToString();
                
                //selectedDivertOrder.OutWarehouseCode = "";
                //selectedDivertOrder.InWarehouseCode = "";
                selectedDivertOrder.OutLocationId = dr["LOCATION_ID_OLD"].ToString();
                selectedDivertOrder.InLocationId = dr["LOCATION_ID_NEW"].ToString();
                
                selectedDivertOrder.Qty = Convert.ToDecimal(dr["OUT_QTY"].ToString());
            }
        }
        private bool Save()
        {
            if (!CheckData())
            {
                return false;
            }
            if (dtpOrderTime.EditValue == null)
            {
                MessageBox.Show("请输入移库时间！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            try
            {
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    selectedDivertOrder.Status = "ICO01";
                    InvDivertOrderBs.SaveDivertOrder(selectedDivertOrder, true);
                    return true;
                }
                if (ThisActionType == ActionType.Modify)
                {

                    SetEntity();
                    selectedDivertOrder.Status = "ICO01";
                    InvDivertOrderBs.SaveDivertOrder(selectedDivertOrder, false);
                    return true;
                }
                if (ThisActionType == ActionType.Approve)
                {
                    //SetEntity();
                    selectedDivertOrder.Status = "ICO03";
                    selectedDivertOrder.ApprovedDate = DateTime.Now;
                    selectedDivertOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    InvDivertOrderBs.SaveApproveDivertOrder2(selectedDivertOrder);
                }


                return true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

        }
        #endregion

        #region Events
        private void frmMaintainStorageChange_Load(object sender, EventArgs e)
        {
            BindComboBox();
            SetField(); 
            BindDataGrid();
        }
        private DataRow mselectedDetail;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            mselectedDetail = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void repProductCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                mselectedDetail["PRODUCT_NAME"] = frm.SelectedProduct.ProductName;
                mselectedDetail["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                mselectedDetail["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                if (mselectedDetail["LOCATION_ID_OLD"].ToString() != "")
                {
                    DataTable dt = InvStorageBs.GetInvStorageByProdAndLocation(mselectedDetail["PRODUCT_ID"].ToString(), mselectedDetail["LOCATION_ID_OLD"].ToString());
                    if (dt!=null)
                    {
                        mselectedDetail["INV_QTY"] = InvStorageBs.GetInvStorageByProdAndLocation(mselectedDetail["PRODUCT_ID"].ToString(), mselectedDetail["LOCATION_ID_OLD"].ToString()).Rows[0]["CURRENT_QTY"].ToString();
                    }

                }
            }
            else 
            {
                mselectedDetail["PRODUCT_NAME"] = "";
                mselectedDetail["PRODUCT_CODE"] = "";
                mselectedDetail["PRODUCT_ID"] = "";
            }


        }

        private void repIn_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainLocationQuery frm = new frmMaintainLocationQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectLocation != null)
            {

                mselectedDetail["WAREHOUSE_NAME_NEW"] = MstLocationBs.GetWarehouseLocationByLocationId(frm.SelectLocation.LocationId).Rows[0]["WAREHOUSE_NAME"].ToString();
                mselectedDetail["LOCATION_CODE_NEW"] = MstLocationBs.GetWarehouseLocationByLocationId(frm.SelectLocation.LocationId).Rows[0]["LOCATION_CODE"].ToString();
                mselectedDetail["LOCATION_ID_NEW"] = frm.SelectLocation.LocationId;
            } 
        }

        private void repOut_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainLocationQuery frm = new frmMaintainLocationQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectLocation != null)
            {

                mselectedDetail["WAREHOUSE_NAME_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(frm.SelectLocation.LocationId).Rows[0]["WAREHOUSE_NAME"].ToString();
                mselectedDetail["LOCATION_CODE_OLD"] = MstLocationBs.GetWarehouseLocationByLocationId(frm.SelectLocation.LocationId).Rows[0]["LOCATION_CODE"].ToString();
                mselectedDetail["LOCATION_ID_OLD"] = frm.SelectLocation.LocationId;
                if (mselectedDetail["PRODUCT_CODE"].ToString() != "")
                {
                    DataTable dt = InvStorageBs.GetInvStorageByProdAndLocation(mselectedDetail["PRODUCT_ID"].ToString(), mselectedDetail["LOCATION_ID_OLD"].ToString());
                    if (dt!=null)
                    {
                        mselectedDetail["INV_QTY"] = InvStorageBs.GetInvStorageByProdAndLocation(mselectedDetail["PRODUCT_ID"].ToString(), mselectedDetail["LOCATION_ID_OLD"].ToString()).Rows[0]["CURRENT_QTY"].ToString();
                    }
                }
            } 
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Approve()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            selectedDivertOrder.Status = "ICO04";
            bool successful=InvDivertOrderBs.UpdateInvDivertOrder(selectedDivertOrder);
            if (successful)
            {
                this.DialogResult = DialogResult.OK;
            }
            
        }
        #endregion

    }
}